package cn.wintersun.baseweb.service.impl.user;


import cn.wintersun.basecommon.common.Result;
import cn.wintersun.basecommon.common.ResultCode;
import cn.wintersun.baseweb.dao.FileDate;
import cn.wintersun.baseweb.mapper.FileDateMapper;
import cn.wintersun.baseweb.service.intrer.user.FileDateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class FileDateServiceImpl implements FileDateService {

    @Autowired
    private FileDateMapper fileDateMapper;

    @Value("${file.upload-folder}")
    private String UPLOAD_FOLDER;
    @Override
    public List<FileDate> getFileDate(Integer userId) {
        return fileDateMapper.getFileData(userId);
    }

    @Override
    public void deleteFileDate(String fileName) {
        fileDateMapper.deleteFileData(fileName);
    }

    @Override
    public void saveFileDate(String originalFilename,String objectName, String remark,int currentId) {
        FileDate fileDate = new FileDate();
        fileDate.setUserId(currentId);
        fileDate.setFilePath(objectName);
        fileDate.setFileName(originalFilename);
        fileDate.setRemark(remark);
        fileDate.setState(0);
        fileDate.setData(LocalDateTime.now());
        fileDateMapper.saveFileData(fileDate);
    }

    @Override
    public void updateFileDate(FileDate fileDate) {
        fileDateMapper.updateFileData(fileDate);
    }

    @Override
    public ResponseEntity<Resource> downloadFile(String fileName) {
        // 假设文件存储在某个特定目录
        String filePath = UPLOAD_FOLDER + fileName;
        File file = new File(filePath);

        if (!file.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(null);
        }

        Resource resource = new FileSystemResource(file);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

}
